package zzh.com.kangkenuo.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.FileCallback;
import com.meizu.cloud.pushsdk.PushManager;
import com.tencent.smtt.export.external.interfaces.GeolocationPermissionsCallback;
import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.xiaomi.mipush.sdk.MiPushClient;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Cookie;
import okhttp3.Response;
import zzh.com.kangkenuo.Constants;
import zzh.com.kangkenuo.EventbusHelper;
import zzh.com.kangkenuo.MyApplication;
import zzh.com.kangkenuo.PublicRequest;
import zzh.com.kangkenuo.R;
import zzh.com.kangkenuo.newutlis.NetMsgEvent;
import zzh.com.kangkenuo.newutlis.PackageUtils;
import zzh.com.kangkenuo.newutlis.Resfine;
import zzh.com.kangkenuo.utils.MapUtils;
import zzh.com.kangkenuo.utils.NetUtils;
import zzh.com.kangkenuo.utils.TotalFunction;
import zzh.com.kangkenuo.utils.Util;
import zzh.com.kangkenuo.utils.X5WebView;

@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends BaseActivity {
    private X5WebView web_view;
    public String JSESSIONID; // 定义一个静态的字段，保存sessionID
    protected Context mContext;
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void getCookie() {
        List<Cookie> cookies = OkHttpUtils.getInstance().getCookieJar().getCookieStore().getAllCookie();
        for (int i = 0; i < cookies.size(); i++) {
            if ("PHPSESSID".equals(cookies.get(i).name())) {// ECM_ID
                JSESSIONID = cookies.get(i).name() + "=" + cookies.get(i).value();
                TotalFunction.WriteData(this, "ECS_ID", JSESSIONID);
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }
            if (null != uploadFiles) {
                uploadFiles.onReceiveValue(null);
                uploadFiles = null;
            }

        }

    }

    @Override
    public void onClick(View view) {

    }

    private void initWebView(X5WebView wv) {
        wv.setWebChromeClient(WebChromeClient);
        wv.addJavascriptInterface(new Resfine(this, web_view), "Resfine");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null); //启动硬件加速
        }
    }

    private WebChromeClient WebChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView webView, int newProgress) {
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                if (progressBar.getVisibility() != View.VISIBLE) {
                    progressBar.setVisibility(View.VISIBLE);
                }
                progressBar.setProgress(newProgress);
            }
            super.onProgressChanged(webView, newProgress);
        }


        @Override
        public void onGeolocationPermissionsShowPrompt(String s, GeolocationPermissionsCallback geolocationPermissionsCallback) {
            geolocationPermissionsCallback.invoke(s, true, false);
            super.onGeolocationPermissionsShowPrompt(s, geolocationPermissionsCallback);
        }

        @Override
        public boolean onJsConfirm(WebView webView, String s, String s1, JsResult jsResult) {
            return super.onJsConfirm(webView, s, s1, jsResult);
        }

        @Override
        public boolean onJsPrompt(WebView webView, String s, String s1, String s2, JsPromptResult jsPromptResult) {
            return super.onJsPrompt(webView, s, s1, s2, jsPromptResult);
        }

        @Override
        public boolean onJsTimeout() {
            return super.onJsTimeout();
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            MainActivity.this.uploadFile = uploadFile;
            openFileChooseProcess();
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
            Log.i("test", "openFileChooser 2");
            MainActivity.this.uploadFile = uploadFile;
            openFileChooseProcess();
        }

        // For Android  > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            MainActivity.this.uploadFile = uploadFile;
            openFileChooseProcess();
        }

        // For Android  >= 5.0
        public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         WebChromeClient.FileChooserParams fileChooserParams) {
            MainActivity.this.uploadFiles = filePathCallback;
            openFileChooseProcess();
            return true;
        }

    };

    private void cancelFileChooseProcess() {
        if (uploadFile != null) {
            uploadFile.onReceiveValue(null);
            uploadFile = null;
        } else if (uploadFiles != null) {
            uploadFiles.onReceiveValue(null);
            uploadFiles = null;
        }
    }

    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "test"), 0);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private AsyncTask<Void, Void, H5PayResultModel> mPayTask = null;

    /**
     * 处理支付宝支付请求，转 native 支付
     */
    private boolean handleAliPayUrl(final WebView view, final String url) {
        Context context = mContext;
        if (!(context instanceof Activity)) {
            return false;
        }

        final PayTask task = new PayTask((Activity) context);
        final String ex = task.fetchOrderInfoFromH5PayUrl(url);
        if (TextUtils.isEmpty(ex)) {
            return false;
        }
        // 启动 native 支付
        if (mPayTask == null || mPayTask.getStatus() != AsyncTask.Status.RUNNING) {
            mPayTask = new AsyncTask<Void, Void, H5PayResultModel>() {

                @Override
                protected H5PayResultModel doInBackground(Void... params) {
                    return task.h5Pay(ex, true);
                }

                /*
                                         * 返回码，标识支付状态，含义如下：
                                         * 9000——订单支付成功
                                         * 8000——正在处理中
                                         * 4000——订单支付失败
                                         * 5000——重复请求
                                         * 6001——用户中途取消
                                         * 6002——网络连接出错
                                         */
                @Override
                protected void onPostExecute(H5PayResultModel result) {
                    super.onPostExecute(result);
                    String returnUrl = result.getReturnUrl();
                    if (!TextUtils.isEmpty(returnUrl)) {
                        final String code = result.getResultCode();
                        switch (code) {
                            case "9000":
                                Toast.makeText(MainActivity.this, "订单支付成功", Toast.LENGTH_LONG).show();
                                view.canGoBack();
                                break;
                            case "4000":
                                Toast.makeText(MainActivity.this, "订单支付失败", Toast.LENGTH_LONG).show();
                                view.canGoBack();
                                break;
                            case "6001":
                                Toast.makeText(MainActivity.this, "用户取消支付", Toast.LENGTH_LONG).show();
                                view.canGoBack();
                                break;
                            case "6002":
                                Toast.makeText(MainActivity.this, "网络连接出错", Toast.LENGTH_LONG).show();
                                view.canGoBack();
                                break;
                        }
                    } else {
                        // 支付结束后应当跳转的url地址
                        view.canGoBack();
                    }
                }
            };
            mPayTask.execute();
        }

        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && (web_view.getUrl().contains("i=10&j=&c=entry&do=shop&m=ewei_shop"))) {//由于history被清理掉，canGoBack()会返回false
            finish();
        } else if (keyCode == KeyEvent.KEYCODE_BACK && (web_view.getUrl().contains("i=10&c=entry&do=shop&m=ewei_shop")
                && web_view.getUrl().toString().length() == 71)) {//由于history被清理掉，canGoBack()会返回false
            finish();
        } else if (keyCode == KeyEvent.KEYCODE_BACK && web_view.canGoBack()) {
            web_view.goBack();
            return true;
        }
        return false;
    }

    /***
     * 防止WebView加载内存泄漏
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (web_view != null) {
            web_view.removeAllViews();
            web_view.destroy();
        }
        MapUtils.stopMap();
        OkHttpUtils.getInstance().cancelTag("");
    }

    /**
     * 获取版本号
     */

    public static void appVersionArguments() {
        Map<String, String> urlParams = new HashMap<>();
        try {
            urlParams.put("op", "update");
            urlParams.put("software_name", "Android");
        } catch (Exception e) {
            e.printStackTrace();
        }
        PublicRequest.doPostRequest(Constants.URL, urlParams, Constants.URL + "APPVERSION");
    }

    private void putData() {
        if (TotalFunction.ReadData(this, Constants.LOGININFO) != null) {
            Map<String, String> addMap = new HashMap<>();
            addMap.put("op", "login");
            addMap.put("userInfo", TotalFunction.ReadData(this, Constants.LOGININFO));
            PublicRequest.doPostRequest(Constants.URL, addMap, "loginInfo");
        } else if (TotalFunction.ReadData(this, Constants.MOBILE) != null) {
            Map<String, String> addMap = new HashMap<>();
            String mz_pushid = String.valueOf(PushManager.getPushId(MyApplication.getContext()));
            String jpush_id = String.valueOf(JPushInterface.getRegistrationID(MyApplication.getContext()));
            addMap.put("op", "mobile_login");
            addMap.put("mobile", TotalFunction.ReadData(this, Constants.MOBILE));
            addMap.put("password", TotalFunction.ReadData(this, Constants.PASSWORD));
            String carrier = android.os.Build.MANUFACTURER;   //获取手机厂商：BRAND /MANUFACTURER
            if (carrier.equalsIgnoreCase("Meizu")) {
                addMap.put("mz_pushid", mz_pushid);
            } else if (carrier.equalsIgnoreCase("Xiaomi")) {
            } else {
                addMap.put("jpush_id", jpush_id);
            }
            MiPushClient.setUserAccount(MyApplication.getContext(), TotalFunction.ReadData(this, Constants.MOBILE), "");
            PublicRequest.doPostRequest(Constants.URL, addMap, "mobileLogin");
        }
    }


    @Override
    public void setContent() {
        setContentView(R.layout.activity_main);
        appVersionArguments();
        mContext = this;
        web_view = (X5WebView) findViewById(R.id.web_view);
        progressBar = new ProgressBar(this, null,
                android.R.attr.progressBarStyleHorizontal);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 10);
        progressBar.setLayoutParams(lp);
        web_view.addView(progressBar);
        getCookie();
        putData();
        MapUtils.startMap();
        NetUtils.setCookie(this, Constants.urls, web_view);
        initWebView(web_view);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        web_view.getView().setOverScrollMode(View.OVER_SCROLL_ALWAYS);
        web_view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                WebView.HitTestResult result = web_view.getHitTestResult();
                if (result != null) {
                    int type = result.getType();
                    if (type == WebView.HitTestResult.IMAGE_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                        final String imgurl = result.getExtra();
                        final String imag = imgurl.substring(imgurl.lastIndexOf("/"));
                        new AlertDialog.Builder(MainActivity.this).setMessage("您确定要保存图片吗？")
                                .setNegativeButton("否", null).setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialogInterface, int i) {
                                OkHttpUtils.get(imgurl).tag(this)
                                        .execute(new FileCallback(Environment.getExternalStorageDirectory()
                                                .getAbsolutePath(), imag.replaceAll("/", "")) {
                                            @Override
                                            public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                                                super.downloadProgress(currentSize, totalSize, progress, networkSpeed);
                                            }

                                            @Override
                                            public void onError(Call call, Response response, Exception e) {
                                                super.onError(call, response, e);
                                                Toast.makeText(MainActivity.this, "保存失败", Toast.LENGTH_LONG).show();
                                            }

                                            @Override
                                            public void onSuccess(File file, Call call, Response response) {
                                                Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                                            }
                                        });
                                dialogInterface.dismiss();
                            }
                        }).show();

                    }
                }
                return true;
            }
        });
    }


    @Override
    public void initComponent() {
    }

    @Override
    public void setListener() {

    }

    @Override
    public void onAfterInit() {
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(NetMsgEvent event) {
        String _msgType = (String) event.getMsgType();
        switch (_msgType) {
            case Constants.URL:
                if (event.getMsgJSONObj().optString("flag").equals("1")) {
                    getCookie();
                    NetUtils.setCookie(this, Constants.urls, web_view);
                } else if (event.getMsgJSONObj().optString("flag").equals("2")) {
                    JSONObject jsonObject = event.getMsgJSONObj();
                    JSONObject object = jsonObject.optJSONObject("data");
                    NetUtils.setCookie(this, object.optString("url"), web_view);
                }
                break;
            case "loginInfo":
                if (event.getMsgJSONObj().optString("flag").equals("1")) {
                } else if (event.getMsgJSONObj().optString("flag").equals("2")) {
                }
                break;
            case "mobileLogin":
                // Toast.makeText(this, event.getMsgJSONObj().optString("msg"), Toast.LENGTH_LONG).show();
                break;
            case Constants.URL + "APPVERSION":
                JSONObject jsonObject = event.getMsgJSONObj();
                JSONObject object = jsonObject.optJSONObject("data");
                if (jsonObject.optString("flag").equals("Success")) {
                    if (!PackageUtils.getCurrentVersion(this).equals(object.optString("software_version"))) {
                        Log.e("appversion", object.optString("update_message"));
                        showAlertDialog(this,
                                object.optString("update_message"),
                                object.optString("url"),
                                object.optString("is_update"));
                    }
                }
                break;
            /**
             * 保存图片
             //Toast.makeText(this, "haha", Toast.LENGTH_LONG).show();
             Bitmap bitmap = Util.createViewBitmap(web_view);
             Util.saveImageToGallery(this, bitmap);*/
        }

    }

    public static void showAlertDialog(final MainActivity context, String description,
                                       final String url, final String is_update) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("有新的版本更新...")
                .setCancelable(false)
                .setMessage(description)
                .setNegativeButton("忽略", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (is_update.equals("1")) {
                            context.finish();
                        } else {
                            dialogInterface.dismiss();
                        }
                    }
                })
                .setPositiveButton("下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        PublicRequest.laodingFile(context, url);
                        dialogInterface.dismiss();
                    }
                }).show();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventbusHelper.register(this);
    }

    @Override
    public void onStop() {
        EventbusHelper.unregister(this);
        super.onStop();
    }


}
